#include "HandleMotionsWithoutModel.h"

#include <QSettings>
#include <QFileDialog>
#include <boost/filesystem.hpp>
#include <MMM/MMMCore.h>
#include <MMM/XMLTools.h>

void handleMissingModelFilePath(std::string &modelFilePath) {
    QSettings settings;
    std::string mmmDefaultPath = std::string(MMMTools_SRC_DIR) + "/data/Model/Winter/mmm.xml";
    boost::filesystem::path mmmDefaultFilePath(mmmDefaultPath);

    std::string fileName = MMM::XML::getFileNameWithoutExtension(modelFilePath);
    std::string objectDefaultPath = std::string(MMMTools_SRC_DIR) + "/data/Model/Objects/" + fileName + "/" + fileName + ".xml";
    std::string folderName = MMM::XML::getFolderName(modelFilePath);
    std::string objectDefaultPath2 = std::string(MMMTools_SRC_DIR) + "/data/Model/Objects/" + folderName + "/" + fileName + ".xml";

    if (boost::filesystem::exists(mmmDefaultFilePath) && modelFilePath.find("mmm.xml") != std::string::npos) {
        modelFilePath = mmmDefaultPath;
        MMM_INFO << "Loading missing mmm model file from default path '" + mmmDefaultPath + "'" << std::endl;
    } else if (boost::filesystem::exists(objectDefaultPath)) {
        modelFilePath = objectDefaultPath;
        MMM_INFO << "Loading missing object model file from default path '" + objectDefaultPath + "'" << std::endl;
    } else if (boost::filesystem::exists(objectDefaultPath2)) {
        modelFilePath = objectDefaultPath2;
        MMM_INFO << "Loading missing object model file from default path '" + objectDefaultPath2 + "'" << std::endl;
    } else {
        QSettings settings;
        modelFilePath = QFileDialog::getOpenFileName(0, QString::fromStdString("Model file could not be loaded from '" + modelFilePath + "'. Choose a matching model file in your file system!"), settings.value("model/searchpath", QString::fromStdString(std::string(MMMTools_SRC_DIR) + "/data/Model")).toString(), QString::fromStdString("model files (*.xml)")).toStdString();
        if (!modelFilePath.empty()) settings.setValue("model/searchpath", QString::fromStdString(modelFilePath));
    }
}
